<?php
class Dashboard_Model extends  Model {
	
	function __construct() {
		parent::__construct();
	}
	
	function xhrInsert() {
		$product_name = $_POST['product_name'];
		$product_id = '';

		do {
			$product_id = $this->randId(10);
			$table_name = 'product';
			$col_name = 'productid';
		} while ($this->existId($table_name, $col_name, $product_id));
		
		$param = array(
			':productid' => $product_id,
			':productname' => $product_name, 
		);
		
		$str_query = 'INSERT INTO product (productid, productname) ' . 
		             'VALUES (:productid, :productname)';
		
		$prepare = $this->db->prepare($str_query);
		$prepare->execute($param);
		
		$data = array(
			'productid' => $product_id,
			'productname' => $product_name, 
		);
				
		echo json_encode($data);
	}
	
	function xhrGetListings() {
		$prepare = $this->db->prepare('SELECT * FROM product');
		$prepare->setFetchMode(PDO::FETCH_ASSOC);
		$prepare->execute();
		
		$data = $prepare->fetchAll();
		echo json_encode($data);
	}
	
	function xhrDeleteListings() {
		$param = array(
			'productid' => $_POST['id']
		);
		$strQuery = 'DELETE FROM product WHERE productid=:productid';
		
		$prepare = $this->db->prepare($strQuery);
		$prepare->execute($param);
		
		$count = $prepare->rowCount();		
		echo json_encode($count);
	}
}